#include "rosterxml.h"

//#include "QXmppPresence.h"

RosterXml::RosterXml(QObject *parent) : QObject(parent)
{
    nameTagMuc = "muc";
    rosterXmlFile = "";
}

bool RosterXml::createRosterXML( QString &xmlFileRoster )
{
    rosterXmlFile = xmlFileRoster;

    /* try to read roster.xml */
    QFile rosterFile(xmlFileRoster);
    if( !rosterFile.open( QIODevice::ReadWrite | QIODevice::Text ) )
    {
        qWarning() << Q_FUNC_INFO <<": Failed to open file for read/write: " <<  xmlFileRoster;
        return false;
    }
    QTextStream stream( &rosterFile );

    QString xmlDocStr = stream.readAll();
    rosterFile.close();

    qDebug() << "xmRoster [" << xmlDocStr << "]";
    xmlDocStr.trimmed();
    if( xmlDocStr == "" )
    {
        xmlDocStr = "<roster/>";
    }

    /* try to parse the xml */
    QString errorMsg = "";
    int errorLine = 0, errorColumn = 0;
    rosterXMLDoc.setContent( xmlDocStr, &errorMsg, &errorLine, &errorColumn );
    if( errorMsg != "" )
    {
        qWarning() << Q_FUNC_INFO <<": Cannot parse xml file. Error at " << errorLine << "," << errorColumn << ": "<<  xmlFileRoster;

        rootRoster = rosterXMLDoc.createElement("roster");
        rosterXMLDoc.appendChild( rootRoster );
    }
    else
    {
        rootRoster = rosterXMLDoc.elementsByTagName("roster").item(0).toElement();
    }

    return true;
}



bool RosterXml::saveRosterXml()
{
    QFile rosterFile(rosterXmlFile);
    if( !rosterFile.open( QIODevice::ReadWrite | QIODevice::Text | QIODevice::Truncate) )
    {
        qWarning() << Q_FUNC_INFO <<": Failed to open file for read/write: " <<  rosterXmlFile;
        return false;
    }
    QTextStream stream( &rosterFile );

    qDebug() << rosterXMLDoc.toString();
    stream << rosterXMLDoc.toString();
    stream.flush();

    rosterFile.close();
    return true;
}



void RosterXml::addMuc( RosterItemModel *itemRoster )
{
    QDomElement nodeMuc = rosterXMLDoc.createElement( nameTagMuc );
    rootRoster.appendChild( nodeMuc );

    QString jid = itemRoster->contactJid();

    bool flJidExists = this->itemExists( jid );
    if( flJidExists ) {
        return;
    }

    /* jid */
    QString s_jid = "jid";
    this->routineAddTextNode( nodeMuc, s_jid, jid );

    /* group */
    QString group = itemRoster->group();
    QString s_group = QString("group");
    this->routineAddTextNode( nodeMuc, s_group, group );

    this->saveRosterXml();
}

void RosterXml::removeMuc(QString &jidRoom)
{
    QDomNodeList jidNodes = rosterXMLDoc.elementsByTagName( "jid" );
    for( unsigned int z=0; z< jidNodes.length(); z++ )
    {
        QDomNode nodeJid = jidNodes.item( z );
        QDomNode jN = nodeJid.firstChild();

        if( jN.isNull() ) { continue; }
        QString _jidRoom = jN.nodeValue();

        if( _jidRoom == jidRoom )
        {
            //qDebug() << "1^^^^^^^^^^^^^^^" << rosterXMLDoc.toString();
            QDomNode nodeMuc = nodeJid.parentNode();
            rootRoster.removeChild( nodeMuc );
            //qDebug() << "2^^^^^^^^^^^^^^^" << rosterXMLDoc.toString();

            this->saveRosterXml();
        }
    }
}


QList<RosterItemModel*> RosterXml::getListMuc()
{
    QDomNodeList listOfMuc = rosterXMLDoc.elementsByTagName( nameTagMuc );

    QList<RosterItemModel*> listRet;

    for( unsigned int z=0; z < listOfMuc.length(); z++ )
    {
        QDomNode nodeMuc = listOfMuc.item( z );
        QDomElement domElementMuc = nodeMuc.toElement();

        QString jid = "";
        QDomNode nJid = domElementMuc.elementsByTagName("jid").item(0);
        QDomNode textNodeJid = nJid.firstChild();
        if( !textNodeJid.isNull() ) {
            jid = textNodeJid.nodeValue();
        }

        QString group = "";
        QDomNode nGroup = domElementMuc.elementsByTagName("group").item(0);
        QDomNode textNodeGroup = nGroup.firstChild();
        if( !textNodeGroup.isNull() ) {
            group = textNodeGroup.nodeValue();
        }

        if( jid != "" )
        {
            //QXmppPresence presence( QXmppPresence::Available );

            RosterItemModel *itemModel = new RosterItemModel( this );
            itemModel->setJid( jid );
            if( group != "" ) {
                itemModel->setGroup("Multi-user chats");
            }
            itemModel->setContactName( "" );
            itemModel->setAvatar( "" );
            itemModel->setUnreadMsg( 0 );
            itemModel->setTextStatus( "" );
            itemModel->setItemType( ROSTER_ITEM_MUC ); //1 - muc

            listRet.append( itemModel );
        }
    }

    return listRet;
}


void RosterXml::routineAddTextNode( QDomElement &rootNode, QString &nodeName, QString &textInfo )
{
    QDomElement nodeInfo = rosterXMLDoc.createElement( nodeName );
    rootNode.appendChild( nodeInfo );
    QDomText textNode = rosterXMLDoc.createTextNode( textInfo );
    nodeInfo.appendChild( textNode );
}


bool RosterXml::itemExists(const QString &bareJid) const
{
    bool retValue = false;

    QDomNodeList jidNodes = rosterXMLDoc.elementsByTagName( "jid" );
    for( unsigned int z=0; z< jidNodes.length(); z++ )
    {
        QDomNode nodeJid = jidNodes.item( z );
        QDomNode jN = nodeJid.firstChild();

        if( jN.isNull() ) { continue; }
        QString _bareJid = jN.nodeValue();

        if( _bareJid == bareJid )
        {
            retValue = true;
            break;
        }
    }

    return retValue;
}

void RosterXml::changeGroup(QString &bareJid, QString &newGroup)
{
}

void RosterXml::addContact( RosterItemModel *itemRoster )
{
}
